<?php


namespace App\Middleware;


use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * Class CheckAuthMiddleware
 * @package App\Middleware
 */
class SignMiddleware implements MiddlewareInterface
{


	/**
	 * @param ServerRequestInterface $request
	 * @param RequestHandlerInterface $handler
	 * @return mixed
	 */
	public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
	{
        $sign = $request->getHeaderLine('authorization');

        $array = $request->getParsedBody();

        $params = [];
        foreach ($array as $key => $value) {
            $params[] = $key . '=' . urlencode($value);
        }
        sort($params);

        $newSign = hash_hmac("sha1", implode('&', $params), 'www.baidu.com');
        $newSign = 'Authorization ' . $newSign;

        if ($sign != $newSign) {
            return response()->write('签名错误~', 500);
        } else {
            return $handler->handle($request);
        }
	}


}
